import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/editaddress.module.css";
import leftImg from "../img/left.png";
import { address_save } from "../api/address";

interface Address {
  id: string;
  uid: string;
  name: string;
  tel: string;
  address: string;
  desc: string;
  default: boolean;
}

type FormFields = Omit<Address, "id" | "uid">;

const FIELD_LABELS: Record<keyof FormFields, string> = {
  name: "收货人",
  tel: "手机号码",
  address: "详细地址",
  desc: "所在地区",
  default: "设为默认地址",
};

const FIELD_ORDER: (keyof FormFields)[] = [
  "name",
  "tel",
  "address",
  "desc",
  "default",
];

const PHONE_REGEX = /^1[3-9]\d{9}$/;

const EditaddressPage: React.FC = () => {
  const user = JSON.parse(localStorage.getItem("user") || "null");
  const navigate = useNavigate();
  const [formData, setFormData] = useState<FormFields>({
    name: "",
    tel: "",
    address: "",
    desc: "",
    default: false,
  });

  const [showHint, setShowHint] = useState(false);
  const [hintMessage, setHintMessage] = useState("");
  const [editId, setEditId] = useState<string | null>(null);

  useEffect(() => {
    const initializeData = () => {
      try {
        const idss = localStorage.getItem("idss");
        const storedData = localStorage.getItem("quanadds");
        const quanadds: Address[] = storedData ? JSON.parse(storedData) : [];

        if (idss) {
          const editAddress = quanadds.find((item) => item.id == idss);
          if (editAddress) {
            const { id, uid, ...rest } = editAddress;
            setFormData({
              ...rest,
              default: Boolean(rest.default),
            });
            setEditId(id);
          }
        }
      } catch (error) {
        console.error("初始化数据失败:", error);
        setHintMessage("数据加载失败");
        setShowHint(true);
        setTimeout(() => setShowHint(false), 2000);
      }
    };

    initializeData();
  }, []);

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const { name, value, type, checked } = e.target;
      setFormData((prev) => ({
        ...prev,
        [name]: type === "checkbox" ? checked : value,
      }));
    },
    []
  );

  const handleSave = useCallback(async () => {
    const { name, tel, address, desc } = formData;

    if (!name.trim() || !tel.trim() || !address.trim() || !desc.trim()) {
      setHintMessage("所有输入框均为必填项！");
      setShowHint(true);
      setTimeout(() => setShowHint(false), 2000);
      return;
    }

    if (!PHONE_REGEX.test(tel)) {
      setHintMessage("请输入有效的手机号码");
      setShowHint(true);
      setTimeout(() => setShowHint(false), 2000);
      return;
    }

    try {
      const response = await address_save({
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: editId || Date.now().toString(),
          uid: user.data.id,
          name: formData.name,
          tel: formData.tel,
          address: formData.address,
          desc: formData.desc,
          default: formData.default ? 1 : 0,
        }),
      });

      const storedData = localStorage.getItem("quanadds");
      const quanadds: Address[] = storedData ? JSON.parse(storedData) : [];
      const updatedAddress = {
        id: editId || Date.now().toString(),
        uid: user.data.id,
        ...formData,
      };

      const newAddresses = editId
        ? quanadds.map((item) => (item.id === editId ? updatedAddress : item))
        : [...quanadds, updatedAddress];

      localStorage.setItem("quanadds", JSON.stringify(newAddresses));

      setHintMessage(editId ? "编辑成功！" : "添加成功！");
      setShowHint(true);
      setTimeout(() => {
        setShowHint(false);
        navigate("/address");
      }, 1000);
    } catch (error) {
      console.error("保存失败:", error);
      setHintMessage("保存失败，请重试！");
      setShowHint(true);
      setTimeout(() => setShowHint(false), 2000);
    }
  }, [formData, editId, navigate, user.data.id]);

  // 修改后的renderFormField函数
  const renderFormField = (field: keyof FormFields, index: number) => {
    const isCheckbox = field === "default";
    return (
      <React.Fragment key={field}>
        <div
          className={
            isCheckbox
              ? `${styles.contentItem} ${styles.defaultAddressItem}`
              : styles.contentItem
          }
        >
          <label className={styles.label}>{FIELD_LABELS[field]}</label>
          {isCheckbox ? (
            <label className={styles.switch}>
              <input
                type="checkbox"
                checked={Boolean(formData[field])}
                onChange={handleInputChange}
                name={field}
              />
              <span className={styles.slider}></span>
            </label>
          ) : (
            <input
              name={field}
              type={field === "tel" ? "tel" : "text"}
              value={formData[field] as string}
              onChange={handleInputChange}
              placeholder={
                field === "desc"
                  ? "街道、门牌号等"
                  : `请输入${FIELD_LABELS[field]}`
              }
              maxLength={field === "tel" ? 11 : undefined}
              className={styles.input}
            />
          )}
        </div>
        {index < FIELD_ORDER.length - 1 && <div className={styles.divider} />}
      </React.Fragment>
    );
  };

  const goBack = () => navigate(-1);

  return (
    <div className={styles.container}>
      {showHint && (
        <div className={styles.hintContainer}>
          <div className={styles.hint}>{hintMessage}</div>
        </div>
      )}

      <div className={styles.top}>
        <img onClick={goBack} src={leftImg} alt="返回" />
        <b>地址编辑</b>
      </div>
      <div style={{ height: "6px" }}></div>
      <div className={styles.content}>
        {FIELD_ORDER.map((field, index) => renderFormField(field, index))}
      </div>

      <div
        className={styles.saveButton}
        onClick={handleSave}
        role="button"
        tabIndex={0}
      >
        保存
      </div>
    </div>
  );
};

export default EditaddressPage;
